package vip.george.order.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author george
 * @since 2023/7/3
 * <p>测试的controller</p>
 */
@Slf4j
@RestController
@RequestMapping("/order/test")
public class TestController {


    /**
     * 这里使用LoadBalancerClient
     * 默认的是RoundRobinLoadBalancer基于轮询的负载均衡策略
     * 也可以选择其他的负载策略：https://blog.csdn.net/weixin_42950079/article/details/128010110
     */
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${user.name}")
    private String username;


    @GetMapping("/add")
    public String query(){
        log.info("订单下单接口测试。。。");
        //RestTemplate 默认没有解析nacos服务名和负载均衡的功能，需要借助LoadBalancerClient组件
        ServiceInstance serviceInstance = loadBalancerClient.choose("stock-service");
        String url = String.format("http://%s:%s/stock/test/reduce",serviceInstance.getHost(),serviceInstance.getPort());
        String response = restTemplate.getForObject(url, String.class);
        log.info(response);
        return response;
    }

    @GetMapping("/test")
    public String test(){
        /* 配置文件中并没有配置user.name
          这里能将值注入到username中是因为springboot启动时获取了当前计算机的环境变量，里面恰巧有user.name变量
          然后将其加载到spring环境中
         */
        System.out.println(username);
        System.out.println(username);
        return "success";
    }


}
